import axios from 'axios';

axios.defaults.headers.post['Content-Type'] = 'application/json';

const fetch = (url, options) => {
  const {
    method = 'get',
    data,
  } = options;

  switch (method.toLowerCase()) {
    case 'get':
      return axios.get(url);
    case 'post':
      return axios.post(url, data);
    case 'put':
      return axios.put(url, data);
    case 'delete':
      return axios.delete(url);
    default:
      return axios(options);
  }
};

export default function request(url, options) {
  return fetch(url, options).then((response) => {
    return response;
  }).catch((error) => {
    const { response } = error;
    let msg;
    let status;
    let otherData = {};
    if (response) {
      const { data, statusText } = response;
      otherData = data;
      status = response.status;
      msg = data.message || statusText;
    } else {
      status = 600;
      msg = 'Network Error';
    }
    return { success: false, status, message: msg, ...otherData };
  });
}
